const pool = require('./db');

class User {
   async findByUsername(username) {
    const [rows] = await pool.query('SELECT * FROM user WHERE username = ?', [username]);
    return rows[0];
  }

   async findById(userId) {
    const [rows] = await pool.query('SELECT * FROM user WHERE user_id = ?', [userId]);
    return rows[0];
  }

   async create(userData) {
    const { username, name, password, user_type, company = null, phone = null } = userData;
    const [result] = await pool.query(
      'INSERT INTO user (username, name, password, user_type, status, company, phone) VALUES (?, ?, ?, ?, "pending", ?, ?)',
      [username, name, password, user_type, company, phone]
    );
    return result.insertId;
  }

   async updateStatus(userId, status) {
    await pool.query('UPDATE user SET status = ? WHERE user_id = ?', [status, userId]);
  }

   async findAll(userType = null, keyword = null) {
    let query = 'SELECT * FROM user';
    const params = [];
    
    if (userType || keyword) {
      query += ' WHERE';
      if (userType) {
        query += ' user_type = ?';
        params.push(userType);
      }
      if (keyword) {
        if (userType) query += ' AND';
        query += ' (username LIKE ? OR name LIKE ?)';
        params.push(`%${keyword}%`, `%${keyword}%`);
      }
    }
    
    const [rows] = await pool.query(query, params);
    return rows;
  }
}

module.exports = new User();